<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>缘淘相机</title>
    <link rel="stylesheet" href="./css/bootstrap.css">
    <link rel="stylesheet" href="./css/bootstrap-icons/bootstrap-icons.css">
    <script src="./js/jquery-3.7.1.min.js"></script>
    <script src="./js/bootstrap.bundle.js"></script>
    <style>
        /* 搜索框 */
        #search-input:focus~#search-suggestion {
            display: block !important;
            border: 2px solid #636466 !important;
            border-top: 0 !important;
        }

        #search-input:hover {
            border: 2px solid #636466 !important;
        }

        #carouselExampleIndicators img {
            height: 400px;
        }

        /* 模态框 */
        @media(min-width: 576px) {
            .modal-dialog {
                max-width: 800px;
                margin: 1.75rem auto;
            }
        }

        .modal-body input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 3px;
            box-sizing: border-box;
        }

        .modal-body span {
            display: block;
            color: red;
            font-size: 14px;
            min-height: 18px;
            /* 确保提示区域有最小高度 */
        }

        button:hover {
            background-color: #0056b3;
        }

        .card:hover {
            transform: scale(1.05);
            transition: all 0.4s ease-in-out;
        }

        /* 轮播图 */
        /* 轮播图容器 */
        .carousel {
            position: relative;
            width: 100%;
            max-width: 1920px;
            overflow: hidden;
            aspect-ratio: 1920/550;
        }

        /* 图片容器 */
        .carousel-images {
            display: flex;
            width: 100%;
            height: 100%;
            transition: transform 0.5s ease-in-out;
            /* 优化过渡动画性能 */
            will-change: transform;
        }

        .carousel-images img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: opacity 0.3s;
            /* 图片淡入效果 */
        }

        /* 指示器（小圆点） */
        .carousel-indicators {
            position: absolute;
            bottom: 20px;
            left: 0;
            right: 0;
            display: flex;
            justify-content: center;
            gap: 10px;
            z-index: 10;
        }

        .carousel-indicators button {
            width: 12px;
            height: 12px;
            border: none;
            border-radius: 50%;
            background-color: rgba(255, 255, 255, 0.5);
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .carousel-indicators button.active {
            background-color: white;
        }

        /* 控制按钮 */
        .carousel-control {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            background-color: rgba(0, 0, 0, 0.3);
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            cursor: pointer;
            z-index: 10;
            transition: background-color 0.3s;
        }

        .carousel-control:hover {
            background-color: rgba(0, 0, 0, 0.6);
        }

        .carousel-control.prev {
            left: 20px;
        }

        .carousel-control.next {
            right: 20px;
        }

        /* 购物车样式 */
        .cart-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }

        .cart-item:last-child {
            border-bottom: none;
        }

        .cart-item .item-info {
            flex-grow: 1;
            margin-left: 15px;
        }

        .cart-item .item-actions {
            display: flex;
            align-items: center;
        }

        .cart-item .quantity-btn {
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid #ddd;
            cursor: pointer;
        }

        .cart-item .quantity {
            width: 40px;
            text-align: center;
            border: 1px solid #ddd;
            border-left: none;
            border-right: none;
        }

        /* 尾巴 */
        .footer a {
            color: #d8d5d5;
            text-decoration: none;
        }

        .footer a:hover {
            color: #fff;
        }
    </style>
</head>

<body>
    <!-- 导航 -->
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="#">缘淘相机<i class="bi bi-camera ml-2"></i></a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <!-- 导航 -->
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="#">首页 <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#products-container">商品展览</a>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                        商品分类
                    </a>
                    <div class="dropdown-menu">
                        <a class="dropdown-item" href="#products-container">单反相机</a>
                        <a class="dropdown-item" href="#products-container">数码相机</a>
                        <a class="dropdown-item" href="#products-container">胶片相机</a>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" href="#products-container">单反摄像头</a>
                        <a class="dropdown-item" href="#products-container">三脚架</a>
                    </div>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#shopCartModal" data-toggle="modal"><i
                            class="bi bi-bag-check mr-1"></i>购物车 <span id="cart-count"
                            class="badge badge-pill badge-danger">0</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#loginModal" data-toggle="modal">登录</a>
                </li>
            </ul>
            <!-- 搜索框 -->
            <div class="input-group ml-2" style="width: 300px;">
                <!-- 搜索框 -->
                <input id="search-input" type="text" class="form-control"
                    style="box-shadow:none; border-radius: 10px 0 0 10px; border: 2px solid #c4c7ce; " placeholder="搜索">
                <!-- 下拉框 -->
                <div id="search-suggestion" class="d-none position-absolute border border-light rounded bg-white"
                    style="top: 36px; z-index: 999;right: 40px;width: 260px;">
                    <ul class="list-inline border-top p-1 text-left">
                        <li class="mt-2"><a class="text-dark">单反相机</a></li>
                        <li class="mt-3"><a class="text-dark">胶片相机</a></li>
                        <li class="mt-3"><a class="text-dark">数码相机</a></li>
                    </ul>
                </div>
                <!-- 按钮 -->
                <div class="input-group-append">
                    <button class="btn btn-outline-dark" type="button" id="basic-addon2" style="height: 37px;">
                        <i class="bi bi-search"></i>
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <!-- 轮播图 -->
    <div class="carousel" id="main-carousel">
        <!-- 图片容器（动态生成图片） -->
        <div class="carousel-images" id="carousel-images"></div>
        <!-- 控制按钮（静态结构+动态事件） -->
        <button class="carousel-control prev" id="prev-btn" aria-label="Previous slide">
            <span>&lt;</span>
        </button>
        <button class="carousel-control next" id="next-btn" aria-label="Next slide">
            <span>&gt;</span>
        </button>
        <!-- 指示器容器（动态生成指示器） -->
        <div class="carousel-indicators" id="carousel-indicators"></div>
    </div>

    <!-- 模态框 + 表单验证  -->
    <div class="modal" id="loginModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">登录/注册</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form action="" method="post" name="myform">
                        <div class="form-group">
                            <label>用户名：</label>
                            <input type="text" name="username" placeholder="只能输入6-20个字母、数字、下划线" id="username"
                                autocomplete="off">
                            <span id="usernameError"></span>
                        </div>
                        <div class="form-group">
                            <label>电子邮箱：</label>
                            <input type="text" name="email" placeholder="输入正确的电子邮箱地址" id="email" autocomplete="off">
                            <span id="emailError"></span>
                        </div>
                        <div class="form-group">
                            <label>密码：</label>
                            <input type="password" name="pwd" placeholder="由字母开头,包含字母、数字、下划线,6-16位" id="pwd"
                                autocomplete="new-password">
                            <span id="pwdError"></span>
                        </div>
                        <div class="form-group">
                            <label>确认密码：</label>
                            <input type="password" name="pwdOk" placeholder="确认密码必须与密码一致" id="pwdOK"
                                autocomplete="new-password">
                            <span id="pwdOKError"></span>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="validateForm()">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 模态框 + 购物车 -->
    <div class="modal" id="shopCartModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">购物车</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="cart-items" id="cart-items">
                        <!-- js脚本 -->
                        <p id="empty-cart-message">购物车是空的</p>
                    </div>
                    <div class="cart-total mt-3">
                        <div class="d-flex justify-content-between">
                            <span>总计:</span>
                            <span id="cart-total">¥0.00</span>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary">结算</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 主体 -->
    <div class="container my-5">
        <!-- 产品分类 -->
        <div class="row mt-4 shaow" id="product-category">
            <div class="col-12 text-center">
                <h4><b>产品分类</b></h4>
                <p>探索我们丰富的相机产品系列，满足您不同的摄影需求</p>
            </div>
            <div class="col-lg-6 col-md-6 col-xs-12 mt-3">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col text-center">
                                <div class="d-flex justify-content-center">
                                    <span
                                        class="rounded rounded-circle d-flex align-items-center justify-content-center"
                                        style="background-color: #dce3f4;width: 70px;height: 70px;">
                                        <i class="bi bi-camera-fill" style="font-size: 26px;color:#0d74e2"></i>
                                    </span>
                                </div>
                                <h5 class="mt-3"><b>单反相机</b></h5>
                                <p>专业级画质体验</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6 col-md-6 col-xs-12 mt-3">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col text-center">
                                <div class="d-flex justify-content-center">
                                    <span
                                        class="rounded rounded-circle d-flex align-items-center justify-content-center"
                                        style="background-color: #dce3f4;width: 70px;height: 70px;">
                                        <i class="bi bi-camera2" style="font-size: 26px;color:#0d74e2"></i>
                                    </span>
                                </div>
                                <h5 class="mt-3"><b>微单相机</b></h5>
                                <p>轻巧便携之选</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6 col-md-6 col-xs-12 mt-3">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col text-center">
                                <div class="d-flex justify-content-center">
                                    <span
                                        class="rounded rounded-circle d-flex align-items-center justify-content-center"
                                        style="background-color: #dce3f4;width: 70px;height: 70px;">
                                        <i class="bi bi-eye" style="font-size: 26px;color:#0d74e2"></i>
                                    </span>
                                </div>
                                <h5 class="mt-3"><b>镜头配件</b></h5>
                                <p>拓展拍摄可能性</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6 col-md-6 col-xs-12 mt-3">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col text-center">
                                <div class="d-flex justify-content-center">
                                    <span
                                        class="rounded rounded-circle d-flex align-items-center justify-content-center"
                                        style="background-color: #dce3f4;width: 70px;height: 70px;">
                                        <i class="bi bi-battery-full" style="font-size: 26px;color:#0d74e2"></i>
                                    </span>
                                </div>
                                <h5 class="mt-3"><b>摄影配件</b></h5>
                                <p>完善您的摄影装备</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 商品 -->
        <div class="row mb-4 mt-4" id="products-container">
            <div class="col-12">
                <h4 class="text-center"><b>商品展览</b></h4>
            </div>
        </div>
        <!-- 动态商品展示 -->
        <div class="row">
            <!-- js脚本 -->
        </div>
    </div>

    <!-- 尾巴 -->
    <footer class="footer bg-dark text-white py-12">
        <div class="container mx-auto px-4">
            <div class="row">
                <div class="col-lg-3 col-md-3 col-xs-3">
                    <h4 class="mt-4"><b>缘淘相机</b></h4>
                    <p style="color: #d8d5d5;">专业相机及配件购物平台，为摄影爱好者提供高品质产品和服务。</p>
                    <a href=""><i class="bi bi-tencent-qq mr-2"></i></a>
                    <a href=""><i class="bi bi-sina-weibo mr-2"></i></a>
                    <a href=""><i class="bi bi-wechat mr-2"></i></a>
                </div>
                <div class="col-lg-3 col-md-3 col-xs-3">
                    <h5 class="mt-4"><b>快速链接</b></h5>
                    <p><a href="#" class="">首页</a></p>
                    <p><a href="#">商品展览</a></p>
                    <p><a href="#">商品分类</a></p>
                    <p><a href="#">关于我们</a></p>
                </div>
                <div class="col-lg-3 col-md-3 col-xs-3">
                    <h5 class="mt-4"><b>客服服务</b></h5>
                    <p><a href="#" class="">帮助中心</a></p>
                    <p><a href="#">联系我们</a></p>
                    <p><a href="#">退换货政策</a></p>
                    <p><a href="#">配送说明</a></p>
                </div>
                <div class="col-lg-3 col-md-3 col-xs-3">
                    <h5 class="mt-4"><b>联系我们</b></h5>
                    <p><a href="#"><i class="bi bi-geo-alt-fill mr-2"></i>武汉市江夏区光谷</a></p>
                    <p><a href="#"><i class="bi bi-telephone-fill mr-2"></i>400-888-8888</a></p>
                    <p><a href="#"><i class="bi bi-envelope-fill mr-2"></i>service@yuantaocamera.com</a></p>
                </div>
            </div>
            <hr>
            <div class="row">
                <div class="col-lg-12 col-md-12 col-xs-12">
                    <p class="text-center" style="color: #c4c7ce;">© 2021-2022 Yuantaocamera. All Rights Reserved.</p>
                </div>
    </footer>

    <script>
        // 轮播图
        // 图片数据
        const images = [
            './img/单反.png',
            './img/胶片.png',
            './img/摄像头.png',
            './img/数码.png'
        ];

        // DOM元素
        const carousel = document.getElementById('main-carousel'); //最外层div
        const imagesContainer = document.getElementById('carousel-images'); //图片容器
        const indicatorsContainer = document.getElementById('carousel-indicators'); //小圆点指示器
        const prevButton = document.getElementById('prev-btn'); //上一个按钮
        const nextButton = document.getElementById('next-btn'); //下一个按钮

        // 当前索引: 默认为0即显示图片索引0
        let currentIndex = 0;
        // 定时器ID: 自动播放定时器
        let autoplayTimer = null;
        // 自动播放间隔(毫秒)
        const autoplayInterval = 3000;
        // 初始化轮播图
        const initialAutoplayInterval = 3000;

        function initCarousel() {
            // 添加图片
            images.forEach(image => {
                const img = document.createElement('img');
                img.src = image;
                imagesContainer.appendChild(img);
            });

            // 添加指示器: 循环创建指示器按钮并添加点击事件监听器
            images.forEach((_, index) => {
                const indicator = document.createElement('button');
                if (index === 0) {
                    indicator.classList.add('active');
                }
                indicator.addEventListener('click', () => goToSlide(index));
                indicatorsContainer.appendChild(indicator);
            });

            // 设置初始位置
            updateCarouselPosition();

            // 添加事件监听器
            prevButton.addEventListener('click', goToPrevSlide); //点击上一个按钮
            nextButton.addEventListener('click', goToNextSlide); //点击下一个按钮
            carousel.addEventListener('mouseenter', pauseAutoplay); //鼠标移到图片上
            carousel.addEventListener('mouseleave', startAutoplay); //鼠标离开图片
            document.addEventListener('keydown', handleKeyPress); // 键盘导航

            startAutoplay();
        }

        // 获取下一张图片索引
        function getNextIndex() {
            return (currentIndex + 1) % images.length;
        }

        // 获取上一张图片索引
        function getPrevIndex() {
            return (currentIndex - 1 + images.length) % images.length;
        }

        // 更新轮播图位置
        function updateCarouselPosition() {
            const offset = -currentIndex * 100;
            imagesContainer.style.transform = `translateX(${offset}%)`;

            // 更新指示器状态
            document.querySelectorAll('.carousel-indicators button').forEach((indicator, index) => {
                if (index === currentIndex) {
                    indicator.classList.add('active');
                } else {
                    indicator.classList.remove('active');
                }
            });
        }

        // 前往指定幻灯片
        function goToSlide(index) {
            if (index !== currentIndex) {
                currentIndex = index;
                updateCarouselPosition();
                resetAutoplay();
            }
        }

        // 前往上一张幻灯片
        function goToPrevSlide() {
            currentIndex = getPrevIndex();
            updateCarouselPosition();
            resetAutoplay();
        }

        // 前往下一张幻灯片
        function goToNextSlide() {
            currentIndex = getNextIndex();
            updateCarouselPosition();
            resetAutoplay();
        }

        // 开始自动播放
        function startAutoplay() {
            if (!autoplayTimer) { //定时器ID为null (未开启), 则开启定时器
                autoplayTimer = setInterval(goToNextSlide, autoplayInterval);
            }
        }

        // 暂停自动播放
        function pauseAutoplay() {
            clearInterval(autoplayTimer);
            autoplayTimer = null;
        }

        // 重置自动播放
        function resetAutoplay() {
            pauseAutoplay();
            startAutoplay();
        }

        // 键盘导航事件处理
        function handleKeyPress(event) {
            if (event.key === 'ArrowLeft') {
                goToPrevSlide();
            } else if (event.key === 'ArrowRight') {
                goToNextSlide();
            }
        }

        // 初始化
        window.addEventListener('DOMContentLoaded', initCarousel);
        // 页面卸载时清理定时器
        window.addEventListener('unload', () => {
            clearInterval(autoplayTimer);
        });

        // 表单验证
        // 获取元素
        const myForm = document.forms.myform;
        const username = myForm.username;
        const email = myForm.email;
        const pwd = myForm.pwd;
        const pwdOK = myForm.pwdOK;

        // 验证用户名
        function validateUsername(str) {
            const regExp = /^[a-zA-Z0-9_]{6,20}$/;
            return regExp.test(str);
        }

        // 验证电子邮箱
        function validateEmail(str) {
            const regExp = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return regExp.test(str);
        }

        // 验证密码
        function validatePassword(str) {
            const regExp = /^[a-zA-Z]\w{5,15}$/;
            return regExp.test(str);
        }

        // 检查确认密码与密码是否一致
        function checkPasswordsMatch(pwd, pwdOK) {
            return pwd.value === pwdOK.value;
        }

        // 显示错误信息
        function showError(spanId, message) {
            const errorSpan = document.getElementById(spanId);
            errorSpan.textContent = message;
        }

        // 清空错误信息
        function clearError(spanId) {
            const errorSpan = document.getElementById(spanId);
            errorSpan.textContent = "";
        }

        // 用户名输入框失去焦点事件
        username.addEventListener('blur', function () {
            if (username.value) {
                const isValid = validateUsername(username.value);
                if (isValid) {
                    clearError('usernameError');
                } else {
                    showError('usernameError', "用户名不符合要求");
                }
            } else {
                showError('usernameError', "用户名不能为空");
            }
        });

        // 电子邮箱输入框失去焦点事件
        email.addEventListener('blur', function () {
            if (email.value) {
                const isValid = validateEmail(email.value);
                if (isValid) {
                    clearError('emailError');
                } else {
                    showError('emailError', "邮箱格式不符合要求");
                }
            } else {
                showError('emailError', "邮箱不能为空");
            }
        });

        // 密码输入框失去焦点事件
        pwd.addEventListener('blur', function () {
            if (pwd.value) {
                const isValid = validatePassword(pwd.value);
                if (isValid) {
                    clearError('pwdError');
                } else {
                    showError('pwdError', "密码不符合要求");
                }
            } else {
                showError('pwdError', "密码不能为空");
            }
        });

        // 确认密码输入框输入事件
        pwdOK.addEventListener('input', function () {
            if (pwdOK.value) {
                const isMatch = checkPasswordsMatch(pwd, pwdOK);
                if (isMatch) {
                    clearError('pwdOKError');
                } else {
                    showError('pwdOKError', "密码与重复密码不一致");
                }
            } else {
                showError('pwdOKError', "请输入确认密码");
            }
        });

        // 表单提交事件
        myForm.addEventListener('submit', function (e) {
            e.preventDefault(); // 阻止表单默认提交行为
            let isValid = true;

            if (!validateUsername(username.value)) {
                showError('usernameError', "用户名不符合要求");
                isValid = false;
            }

            if (!validateEmail(email.value)) {
                showError('emailError', "邮箱格式不符合要求");
                isValid = false;
            }

            if (!validatePassword(pwd.value)) {
                showError('pwdError', "密码不符合要求");
                isValid = false;
            }

            if (!checkPasswordsMatch(pwd, pwdOK)) {
                showError('pwdOKError', "密码与重复密码不一致");
                isValid = false;
            }

            if (isValid) {
                console.log(username.value);
                console.log(email.value);
                console.log(pwd.value);
                // 如果验证通过，可以通过AJAX提交表单或执行其他操作
                // 这里保留原有的表单提交行为，仅用于测试
                // myForm.submit();
            } else {
                alert("验证失败，请检查输入");
            }
        });

        // 购物车
        // 获取元素
        let cart = [];
        let cartItems = document.getElementById('cart-items');
        let cartTotal = document.getElementById('cart-total');
        let cartCount = document.getElementById('cart-count');
        let productsContainer = document.getElementById('products-container');

        // 模拟商品数据
        let products = [
            { id: 1, name: '专业单反相机', price: 8999, image: './img/商品1.png' },
            { id: 2, name: '高级数码相机', price: 6100, image: './img/商品2.png' },
            { id: 3, name: '复古胶片相机', price: 699, image: './img/商品3.png' },
            { id: 4, name: '广角镜头', price: 5980, image: './img/商品4.png' },
            { id: 5, name: '微距镜头', price: 3990, image: './img/商品5.png' },
            { id: 6, name: '专业三脚架', price: 445, image: './img/商品6.png' }
        ];

        // 商品异步
        fetch('goods.json')
            .then(response => {
                // 处理响应状态
                if (!response.ok) throw new Error(`HTTP错误:${response.status}`)
                return response.json()// 解析JSON数据
            })
            .then(data => {
                // 使用解析后的数据
                console.log(data);
            })
            .catch(error => {
                // 捕获请求错误
                console.error('抱歉，您请求失败了：', error);
            })

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function () {
            renderProducts();
            updateCart();
        });

        // 渲染商品列表
        function renderProducts() {
            products.forEach(product => {
                const card = document.createElement('div');
                card.className = 'col-md-4 col-sm-6 product-card mt-3';
                card.innerHTML = `
                    <div class="card h-100 mt-3">
                        <img src="${product.image}" class="card-img-top" alt="${product.name}">
                        <div class="card-body">
                            <h5 class="card-title">${product.name}</h5>
                            <p class="card-text">¥${product.price.toFixed(2)}</p>
                            <button class="btn btn-primary" onclick="addToCart(${product.id})">
                                <i class="bi bi-cart-plus mr-1"></i>加入购物车
                            </button>
                        </div>
                    </div>
                `;
                productsContainer.appendChild(card);
            });
        }

        // 添加商品到购物车
        function addToCart(productId) {
            const product = products.find(p => p.id === productId);
            if (!product) return;

            const existingItem = cart.find(item => item.id === productId);

            if (existingItem) {
                existingItem.quantity += 1;
                // 更新购物车中的数量
                alert(`已将"${product.name}"的数量增加到 ${existingItem.quantity}`);
            } else {
                cart.push({
                    id: product.id,
                    name: product.name,
                    price: product.price,
                    quantity: 1
                });
                // 商品添加到购物车提示
                alert(`"${product.name}"已添加到购物车`);
            }

            updateCart();
        }

        // 更新购物车显示
        function updateCart() {
            // 清空购物车内容
            cartItems.innerHTML = '';

            // 计算商品总数
            const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
            cartCount.textContent = totalItems;

            // 如果购物车为空，显示空购物车消息
            if (cart.length === 0) {
                cartItems.innerHTML = '<p id="empty-cart-message">购物车是空的</p>';
                cartTotal.textContent = '¥0.00';
                return;
            }

            // 计算总价
            let totalPrice = 0;

            // 渲染购物车商品
            cart.forEach(item => {
                const itemTotal = item.price * item.quantity;
                totalPrice += itemTotal;

                const cartItem = document.createElement('div');
                cartItem.className = 'cart-item';
                cartItem.innerHTML = `
                    <div class="item-info">
                        <h6>${item.name}</h6>
                        <p>¥${item.price.toFixed(2)} x ${item.quantity}</p>
                    </div>
                    <div class="item-actions">
                        <div class="quantity-btn" onclick="decreaseQuantity(${item.id})">-</div>
                        <div class="quantity">${item.quantity}</div>
                        <div class="quantity-btn" onclick="increaseQuantity(${item.id})">+</div>
                        <button class="btn btn-sm btn-danger ml-3" onclick="removeFromCart(${item.id})">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                `;
                cartItems.appendChild(cartItem);
            });

            // 更新总价
            cartTotal.textContent = `¥${totalPrice.toFixed(2)}`;
        }

        // 增加商品数量
        function increaseQuantity(productId) {
            const item = cart.find(item => item.id === productId);
            if (item) {
                item.quantity += 1;
                updateCart();
                // 提示 购物车内商品数量增加
                alert(`已将"${item.name}"的数量增加到 ${item.quantity}`);
            }
        }

        // 减少商品数量
        function decreaseQuantity(productId) {
            const item = cart.find(item => item.id === productId);
            if (item && item.quantity > 1) {
                item.quantity -= 1;
                updateCart();
                // 提示 购物车内商品数量减少
                alert(`已将"${item.name}"的数量减少到 ${item.quantity}`);
            } else if (item && item.quantity === 1) {
                removeFromCart(productId);
            }
        }

        // 从购物车移除商品
        function removeFromCart(productId) {
            const item = cart.find(item => item.id === productId);
            if (item) {
                // 提示 购物车内商品移除
                alert(`已从购物车移除"${item.name}"`);
                cart = cart.filter(item => item.id !== productId);
                updateCart();
            }
        }

        // 异步
        fetch()
    </script>
</body>

</html>